'use strict';

/**
 * @ngdoc function
 * @name sfhtHaitaoCmsApp.controller:ActivityPageManagerCtrl
 * @description
 * # ActivityPageManagerCtrl
 * Controller of the sfhtHaitaoCmsApp
 */
angular.module('sfhtHaitaoCmsApp')
	.controller('ActivityPageManagerCtrl', function($scope, $route, $modal, $injector, $log, AcitivityStore, CONST_PC_URL, CONST_H5_URL, store) {
		var DEFAULT_PAGE_SIZE = 25;
		$scope.topics = [];
		$scope.totalItems = 1;
		$scope.currentPage = 1;
		$scope.searchKeywords = null;
		$scope.searchOption = 'searchByKeywords';
		$scope.profile = store.get("profile");
		var exitedCondition = AcitivityStore.get("activityCondition") || {"pageType":0,
																			"showAbandoned": false,
																			"showAbandoned": false,
																			"periodOptions": 'LAST_ONE_WEEK'};
		$scope.pageType = exitedCondition["pageType"];
		$scope.showAbandoned = exitedCondition["showAbandoned"];
		$scope.isOnlyShowMine = exitedCondition["isOnlyShowMine"];
		$scope.periodOptions = exitedCondition["periodOptions"];

		var topicService = $injector.get("TopicService");



		/**
		 * 查询专题列表
		 * @param  {Boolean} 是否只查询我编辑的页面
		 * @param  {string} 搜索关键词
		 * @param  {int} 分页的页码
		 * @param  {int} 页面类型0:pc,1:h5
		 * @return {array}
		 */
		var getTopicList = function(periodOptions, isOnlyShowMine, searchKeywords, pageIndex, pageType, showAbandoned) {
			var pagedQueryOption = {
				pageIndex: pageIndex,
				pageSize: DEFAULT_PAGE_SIZE,
			};
			if (searchKeywords) {
				//如果关键词为全数字则为查询专题编号，否则为查询专题名称
				if (/^[1-9]+[0-9]*$/.test(searchKeywords.trim())) {
					searchKeywords = "id:" + searchKeywords;
				} else {
					searchKeywords = searchKeywords;
				}
			}

			//记录查询条件
			var activityCondition = {
				"periodOptions": periodOptions,
				"isOnlyShowMine": isOnlyShowMine,
				"pageType": pageType,
				"showAbandoned": showAbandoned
			};
			AcitivityStore.set("activityCondition",activityCondition);

			topicService.getTopicList(periodOptions, isOnlyShowMine, searchKeywords, pageType, pagedQueryOption, showAbandoned)
				.then(function(data) {
					$scope.topics = data.cmsTopicList;
					$scope.totalItems = data.pageInfo.totalCount;
					$scope.currentPage = data.pageInfo.pageIndex
				});
		};

		/**
		 * 设置关注或是取消关注
		 * @param  {int} 专题Id
		 * @param  {boolean} 是否关注，true表示关注，false表示取消关注
		 * @param  {string} 错误信息
		 * @return {array}
		 */
		function watchSetting(topicId, isWatch, errorMsg){
			topicService.setWatch(topicId, isWatch)
				.then(function(data) {
					var topic = _.findWhere($scope.topics, {
						id: topicId
					});
					topic.watch = isWatch;
				},
				function(data) {
					alert(errorMsg + ":" + data)
				});
		}

		/**
		 * 删除专题或是恢复专题
		 * @param  {int} 专题Id
		 * @param  {boolean}  true表示删除，false表示恢复删除的专题
		 * @param  {string} 错误信息
		 * @return {array}
		 */
		function delOrRecover(topicId, isDelete, errorMsg){
			topicService.setTopicDelete(topicId, isDelete)
				.then(function(data) {
					$route.reload()
					// window.location.reload();
				},
				function(data) {
					alert(errorMsg + ":" + data)
				});
		}

		//根据设备类型查询对应的专题页面
		$scope.changeDeviceType = function(pageType) {
			$scope.pageType = pageType;
			$scope.search();
		};

		//根据条件查询专题
		$scope.search = function() {
			getTopicList($scope.periodOptions, $scope.isOnlyShowMine, $scope.searchKeywords, $scope.currentPage, $scope.pageType, $scope.showAbandoned);
		};

		/**
		 * 设置关注
		 * @param  {int} 专题Id
		 * @return {array}
		 */
		$scope.watch = function(topicId) {
			watchSetting(topicId, true, "关注失败");
		};

		/**
		 * 取消关注
		 * @param  {int} 专题Id
		 * @return {array}
		 */
		$scope.unwatch = function(topicId) {
			watchSetting(topicId, false, "取消关注失败");
		};

		/**
		 * 删除专题
		 * @param  {int} 专题Id
		 * @return {array}
		 */
		$scope.delete = function(topicId) {
			if (window.confirm("确定删除?")) {
				delOrRecover(topicId, true, "删除失败");
			}
		};

		/**
		 * 恢复删除的专题
		 * @param  {int} 专题Id
		 * @return {array}
		 */
		$scope.rollback = function(topicId) {
			delOrRecover(topicId, false, "恢复失败");
		};
		/**
		 * @description 编辑专题信息
		 * @param  {[type]}
		 * @return {[type]}
		 */
		$scope.open = function(topic, $index) {
			var modal = $modal.open({
				animation: true,
				templateUrl: 'topic.property.edit.html',
				controller: 'ModalUpdateTopicCtrl',
				resolve: {
					topic: function() {
						return topic;
					}
				}
			});
			modal.result.then(function(topic) {
				$scope.topics[$index] = topic;
			}, function() {
				$route.reload();
				// window.location.reload(true);
			});
		};

		/**
		 * 根据关键字过滤当前页面的数据
		 */
		$scope.isSearch = function(searchKeywords) {
			if (searchKeywords && searchKeywords.length > 0) {
				return searchKeywords;
			} else {
				return;
			}
		}
	})
	.controller('ModalUpdateTopicCtrl', function($scope, $filter,$modalInstance, $injector, topic, Uploader) {
		$scope.topic = topic;
		$scope.topic.fileName = topic.bannerImg;
		function convertDateToString(dateValue) {
			if(dateValue && dateValue > 0){
            	return $filter('date')(dateValue, 'yyyy-MM-dd HH:mm');
			}
			else{
				return "";
			}
        }

        $scope.changeFile = function(imgName) {
	      Uploader.uploadFile($scope, imgName);
	    };


        if(topic.starttime){
        	$scope.topic.starttime = convertDateToString(topic.starttime);
        }
        if(topic.endtime){
         	$scope.topic.endtime = convertDateToString(topic.endtime);
        }
		//日历
        $scope.initTime = function() {
            $('.datetimepicker').datetimepicker({
                format: 'YYYY-MM-DD HH:mm'
            })
        };

        $scope.dateChange = function(topic, index) {
        	if(index == 1){
        		topic.starttime = $('.datetimepicker1').val();
        	}
            if(index == 2){
        		topic.endtime = $('.datetimepicker2').val();
        	}
        };

		/**
		 * 修改专题属性
		 * @param  {object} 专题对象
		 * @return {array}
		 */
		$scope.save = function(topic) {
			if(!topic.starttime || !topic.endtime){
		    	alert("开始时间，结束时间不能为空！！");
		    	return false;
		    }
			topic.starttime = new Date(topic.starttime).getTime();
			topic.endtime = new Date(topic.endtime).getTime();
			topic.bannerImg = topic.fileName;
			var topicService = $injector.get("TopicService");
			topicService.updateTopic(topic)
				.then(function(data) {
					$modalInstance.close(topic);
				}, function(data) {
					alert(data);
				});
		};
		$scope.cancel = function() {
			$modalInstance.dismiss('cancel');
		};
	});